import { createRequire } from 'node:module';

import { PROJ_PATH } from '../../utils/index.mjs';

const require = createRequire(import.meta.url);
const fs = require('node:fs');
const path = require('node:path');

export function createDesignHandler(app, logger) {
  // =================设计保存、查询 Begin============================
  // 获取设计映射文件
  app.get('/design/mapping', async (req, res) => {
    const mappingPath = path.resolve(PROJ_PATH, `mapping.json`);
    try {
      const data = fs.readFileSync(mappingPath, 'utf8');
      res.send({ code: 200, data: data || [], msg: 'mapping.json 存在' });
    } catch (error) {
      logger.error(error);
      res.send({ code: 500, data: [], msg: 'mapping.json 不存在' });
    } finally {
      res.end();
    }
  });

  // 获取映射文件
  app.get('/design/project/:id', async (req, res) => {
    const id = req.params.id;
    if (!id) {
      res.send({ code: 500, msg: '参数错误' });
      return;
    }
    try {
      const projectPath = path.resolve(PROJ_PATH, `${id}.json`);
      const data = fs.readFileSync(projectPath, 'utf8');
      res.send({ code: 200, data, msg: 'project.json 存在' });
    } catch (error) {
      logger.error(error);
      res.send({ code: 500, msg: 'project.json 不存在' });
    } finally {
      res.end();
    }
  });

  // 删除映射文件
  app.delete('/design/delete/:id', async (req, res) => {
    const id = req.params.id;
    if (!id) {
      res.send({ code: 500, msg: '参数错误' });
      return;
    }
    let data = '';
    req.on('data', (chunk) => {
      data += chunk;
    });
    req.on('end', async () => {
      try {
        data = JSON.parse(data); // 将JSON字符串解析成对象
        // 映射文件
        const mappingPath = path.resolve(PROJ_PATH, `mapping.json`);
        fs.writeFileSync(mappingPath, JSON.stringify(data.mapping));
        // 只删除映射文件，不删除内容文件
        const projectPath = path.resolve(PROJ_PATH, `${id}.json`);
        if (fs.existsSync(projectPath)) {
          const targetPath = path.resolve(PROJ_PATH, `backup_${id}.json`);
          fs.copyFileSync(projectPath, targetPath);
          // fs.unlink(projectPath, (err) => {
          //   if (err) {
          //     logger.error(err);
          //     res.send({ code: 500, msg: '删除失败' });
          //   }
          // });
        }
        res.send({ code: 200, msg: '删除成功' });
      } catch (error) {
        logger.error(error);
        res.send({ code: 500, msg: '文件不存在' });
      } finally {
        res.end();
      }
    });
  });
  // 保存设计文件
  app.post('/design/save/:id', (req, res) => {
    const id = req.params.id;
    if (!id) {
      res.send({ code: 500, msg: '参数错误' });
      return;
    }
    let data = '';
    req.on('data', (chunk) => {
      data += chunk;
    });
    req.on('end', async () => {
      try {
        data = JSON.parse(data); // 将JSON字符串解析成对象
        // 映射文件
        const mappingPath = path.resolve(PROJ_PATH, `mapping.json`);
        fs.writeFileSync(mappingPath, JSON.stringify(data.mapping));
        // 项目文件
        const projectPath = path.resolve(PROJ_PATH, `${id}.json`);
        fs.writeFileSync(projectPath, JSON.stringify(data.schema));
        res.send({ code: 200, msg: '保存成功' });
      } catch (error) {
        logger.info(error);
        res.send({ code: 500, msg: '保存失败' });
      } finally {
        res.end();
      }
    });
  });

  // =================设计保存、查询 End============================
}
